<template>
  <div id="MultiText" v-loading="loading">
    <!-- 数据输入部分 -->
    <el-row type="flex" class="row-bg" justify="center">
      <el-col :span="20">
        <el-tabs type="border-card" v-model="activeName">
          <!-- 文本输入框 -->
          <el-tab-pane name="文件上传">
            <span slot="label" class="tab_data_input">
              <i class="el-icon-document"></i>
              文件上传
            </span>
            <el-divider></el-divider>
            <el-upload
              class="upload-drag"
              action=""
              drag
              ref="upload"
              :file-list="fileList"
              :auto-upload="false"
              :on-change="onChange"
              :before-upload="beforeUpload"
              :accept="'.zip'">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                选择或拖放数据文件
                <div>支持上传.zip</div>
              </div>
            </el-upload>
            <div style="width: 600px; text-align: left; margin: auto;">
              <el-button
                @click="downloadFile"
                plain
                size="mini"
                icon="el-icon-download"
              >下载模板</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
        <div class="modal-wrapper" style="margin-top: 20px;">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="任务名" prop="taskName">
              <el-input v-model="form.taskName" clearable size="small" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="任务类型" prop="taskType">
              <el-select v-model="form.taskType" size="small" placeholder="请选择" clearable>
                <el-option
                  v-for="(item, index) in taskTypeList"
                  :key="index"
                  :value="item.id"
                  :label="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
    <el-row type="flex" pull="2" push="2" justify="end" class="el-row-stype">
      <el-button type="primary" @click="submit()">提交分析任务</el-button>
    </el-row>
  </div>
</template>
<script>
import request from '@/modules/index/utils/request';

export default {
  name: "MultiText",
  data() {
    return {
      loading: false,
      typeCHs: {
        car: "汽车",
        ecommerce: "电商",
        opinion: "舆情",
      },
      selectModel: "文本输入",
      activeName: "文件上传",
      textarea: "",
      // 选择类别行业品类的待选框数据
      startAnalyDataOptions: {
        types: [],
        industries: [],
        categories: [],
      },
      // 选择类别行业品类的数据
      startAnalyData: {
        type: "",
        industry: "",
        category: "",
      },
      fileList: [],
      form: {
        taskName: '',
        taskType: '',
      },
      rules: {
        taskName: { required: true, message: '请输入任务名', trigger: 'blur' },
        taskType: { required: true, message: '请选择任务类型', trigger: 'change' },
      },
      taskTypeList: [
        { id: '1001', name: '通用ocr' },
      ]
    };
  },
  computed: {},
  // 页面加载完成执行的方法
  mounted() {
  },
  methods: {
    async submit () {
      if (!this.$common.doSubmit('form', this)) return;
      if (!this.fileList.length) {
        this.$message({ type: 'warning', message: '请提交文件' });
        return;
      }
      const formData = new FormData();
      formData.append('File',  this.fileList[0].raw);
      formData.append('taskName', this.form.taskName);
      formData.append('taskType', this.form.taskType);
      formData.append('creator', this.$store.getters.userName || '');
      this.loading = true;
      try {
        const res = await this.$store.dispatch('openAbilityPlatformPredictTaskUpload', formData);
        const result = res.data || {};
        if (result.success) {
          const parmas = result.data || {};
          const res2 = await this.$store.dispatch('openAbilityPlatformPredictTaskIdOcrMulti', parmas);
          const result2 = res2.data || {};
          if (result2.success) {
            this.$message({ type: 'success', message: '提交成功' });
            this.$confirm('是否跳转至分析任务列表?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$router.push('/openAbility');
            }).catch(() => {});
          } else {
            this.$message({ type: 'error', message: '提交失败' });
          }
        } else {
          this.$message({ type: 'error', message: '提交文件失败' });
        }
      } catch (e) {
        console.error(e);
      }
      this.loading = false;
    },
    topNClick() {
      let that = this;
      // 根据 n来 构造 图 和 显示的数
      if (that.topN.allrows.length === 0) {
        this.$message.warning("错了哦，你还没提交分析呢，现在啥都看不到");
      } else {
        that.wordFrequencyData.rows = listTopN(that.topN.n, that.topN.allrows);
        that.topN.desc = that.wordFrequencyData.rows.reduce(
          // pre 前一次的结果 , cru 现在的值, index 索引, allarr 整个数组 initialValue 可选。传递给函数的初始值
          // (pre,cur,index,allarr) =>{},initialValue
          (pre, cur) => {
            return pre + cur.word + ":\t" + cur.count + "\n";
          },
          ""
        );
      }
    },
    // 上传文件之前判断文件类型
    beforeUpload(file) {
      let isZip = false;
      const type = file.type;
      if (type === 'application/zip') isZip = true;
      return isZip;
      // let isExcelxls = file.type === "application/vnd.ms-excel";
      // let isExcelxlsx =
      //   file.type ===
      //   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      // let isTxt = file.type === "text/plain";
      // if (!(isExcelxls || isExcelxlsx || isTxt)) {
      //   this.$message.warning("上传的文件不是xls, xlsx, txt");
      // }
      // return isExcelxls || isExcelxlsx || isTxt;
    },
    onChange (files, fileList) {
      this.fileList = [files];
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，请删除后继续上传`);
    },
    handleChange(file, fileList) {
      if (fileList.length > 1) {
        this.fileList = fileList.slice(-1);
      }
    },
    uploadSuccess(file) {
      let params = new FormData();
      params.append("file", file.file);
      request("/analyze/onecommet", {
        method: "post",
        data: params,
        headers: { "Content-Type": "multipart/form-data;charset=utf-8" },
      })
        // this.ajax
        // .post("/upload/testuploadimg", params)
        .then((res) => {
          if (res.status == "success") {
            this.$message.success(res.message);
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    startAnaly() {
      let that = this;
      var postUrl = "";
      var startAnalyParams = {};
      startAnalyParams["type"] = this.startAnalyData.type;
      startAnalyParams["industry"] = this.startAnalyData.industry;
      startAnalyParams["domain"] = this.startAnalyData.category;
      if (that.selectModel == "文本输入") {
        postUrl = "/remoteAnalyze/multiTextRunData";
        if (that.textarea == "" || that.textarea == null) {
          this.$message.error("分析文本不能为空，请输入分析文本");
          return;
        }
        startAnalyParams["comments"] = that.textarea;
      } else if (that.selectModel == "文件上传") {
        postUrl = "/remoteAnalyze/runData";
        if (that.fileList.length == 0) {
          this.$message.error("请先上传分析文件再分析");
          return;
        }
        startAnalyParams["fileName"] = that.fileList[0].name;
      } else {
        this.$message.error("请选择正确文本输入方式");
        return;
      }
      request(postUrl, {
        method: "post",
        data: startAnalyParams,
      }).then((res) => {
        // http.post(postUrl, startAnalyParams).then((res) => {
        var code = res.data.code;
        if (code == "200") {
          var id = res.data.result.JobId;
          var type = res.data.result.type;
          if (type == "start") {
            this.$message({
              showClose: true,
              message: "任务:" + id + "启动成功，请在任务列表中查看对应状态",
              type: "success",
              duration: 0,
            });
          } else {
            this.$message({
              message: "任务:" + id + "启动时出现未知错误",
              type: "error",
            });
          }
        } else {
          this.$message.error(res.data.result);
        }
      });
    },
    // 下载模板
    async downloadFile () {
      try {
        await this.$store.dispatch('openAbilityPlatformPredictTaskGetFile', {
          projectType: 'ocr_detection'
        });
      } catch (e) {
        console.error(e);
      }
    }
  },
  // 在一个初始宽度未知的容器内绘制图表时，因为无法获取宽度，所以图表会绘制失败，解决的办法是在容器宽度已知后， 调用echarts的resize方法。
  watch: {
    // 类别选项选择/变化了后,行业数据需要刷新,品类全部删除
    "startAnalyData.type": function (newType) {
      //监听特定的属性，这样写

      // 通过 api 获取行业的数据
      request("/label/getIndustry", {
        method: "post",
        data: { type: newType },
      })
        // http
        // .post("/label/getIndustry", { type: newType }) // TODO 这里暂时还没有接口，等后台提供，肯定要传参： 类别：
        .then((res) => {
          // 加载行业数据
          var arrayData = Object.values(res.data.result)[0];
          var industryArray = new Array();
          for (var i = 0; i < arrayData.length; i++) {
            var arr = {
              industry: arrayData[i],
              option: arrayData[i],
            };
            industryArray[i] = arr;
          }
          this.startAnalyDataOptions.industries = industryArray;
          // 清空品类数据
          //this.startAnalyDataOptions.categories = [];
          if (arrayData.length > 0) {
            this.startAnalyData.industry = arrayData[0];
          }
        });
    },
    // 行业选项选择/变化了后,品类数据需要刷新
    "startAnalyData.industry": function (newIndustry) {
      //监听特定的属性，这样写

      // 通过 api 获取品类的数据
      request("/label/getDomain", {
        method: "post",
        data: {
          type: this.startAnalyData.type,
          industry: newIndustry,
        },
      })
        // http
        //   .post("/label/getDomain", {
        //     type: this.startAnalyData.type,
        //     industry: newIndustry,
        //   }) // TODO 这里暂时还没有接口，等后台提供，肯定要传参： 类别： 行业：
        .then((res) => {
          var arrayData = Object.values(res.data.result)[0];
          var domainArray = new Array();
          for (var i = 0; i < arrayData.length; i++) {
            var arr = {
              category: arrayData[i],
              option: arrayData[i],
            };
            domainArray[i] = arr;
          }
          // 加载品类数据
          this.startAnalyDataOptions.categories = domainArray;
          if (arrayData.length > 0) {
            this.startAnalyData.category = arrayData[0];
          }
        });
    },
    activeName(v) {
      this.$nextTick(() => {
        this.selectModel = v;
        console.log(v);
      });
    },
  },
};
function listTopN(n, l) {
  // 如果 n 太大了,就返回所有的
  if (l.length < n) {
    return l;
  } else {
    return l.slice(0, n);
  }
}
//颜色对象
function Color() {
  return "#" + Math.floor(Math.random() * 16777215).toString(16);
}
</script>
<!-- Add "scoped" attribute to limit CSS to this components only -->
<style lang="less" scoped>
.row-bg {
  background-color: #f9fafc;
  padding: 20px;
}
.el-row-stype {
  margin-top: 20px;
  padding: 0.25rem;
}
.tag-margin {
  margin: 0 5px 5px 0;
  color: #5c3317;
}
.top-margin {
  margin-top: 0.75rem;
}
.el-row-tab {
  min-height: 25rem;
}

.upload-drag {
  display: inline-block;
  text-align: center;
  cursor: pointer;
  outline: 0;
}
.upload-drag /deep/ .el-upload {
  width: 600px;
}
.upload-drag /deep/ .el-upload-dragger {
  width: 600px;
}
/*数据输入部分tab*/
// .tab_data_input {
  // font-size: 20px;
// }
/* 自定义 v-charts 没有数据显示的状态 */
.data-empty {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.7);
  color: #888;
  font-size: 14px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
#MultiText {
  text-align: center;
}
</style>
